package studio.raptor.hub.in;

import java.io.UnsupportedEncodingException;

import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import studio.raptor.hub.common.exception.HubInException;
import studio.raptor.hub.in.entity.ServerProxyReq;


public abstract class ServerProxy {
    private static final Logger log = LoggerFactory.getLogger(ServerProxy.class);
    private HttpClient httpClient;
    private String serverUrl;
    private String message;

    public ServerProxy(HttpClient httpClient) {
        this.httpClient = httpClient;
    }



    public String queryServerMsg(ServerProxyReq serverProxyReq) throws Exception{
        this.serverUrl = serverProxyReq.getUrl();
        this.message = getMessage(serverProxyReq.getParams());
        if (log.isDebugEnabled()){
            log.debug("serverProxyReq url->{} ,params->{}", new Object[]{serverProxyReq.getUrl(),serverProxyReq.getParams()});
        }
        String response = queryMsg();
        String jsonResult= handleResponse(response);
        if (log.isDebugEnabled()){
            log.debug("ServerProxy Server->{} ,jsonResult->{}", new Object[]{serverUrl,jsonResult});
        }
        return jsonResult;
    }

    protected abstract String handleResponse(String response);

    protected abstract String getMessage(Long... params);

    private String queryMsg() throws Exception {
        HttpPost request = this.buildRequest(serverUrl, message);
        HttpResponse httpResponse = this.httpClient.execute(request);
        String response = EntityUtils.toString(httpResponse.getEntity(),HTTP.UTF_8);
        int code = httpResponse.getStatusLine().getStatusCode();
        if(code != HttpStatus.SC_OK) {
            throw new HubInException(serverUrl + "服务异常！");
        } else {
            if(log.isDebugEnabled()) {
                log.debug("send serverUrl -> {},message -> {},response->{}", new Object[]{serverUrl, message, response});
            }
            return response;
        }
    }

    private HttpPost buildRequest(String url, String message) throws UnsupportedEncodingException {
        StringEntity entity = new StringEntity(message);
        HttpPost request = new HttpPost(url);
        request.setEntity(entity);
//        Content-Type:text/xml;charset=UTF-8
        Header header = new BasicHeader("Content-Type","text/xml;charset=UTF-8");
        request.setHeader(header);
        return request;
    }
}
